<template>
  <div class="userSubmit">
      <!-- <h2>用户商品提交</h2> -->
      <div class="title">
        <el-breadcrumb separator-class="el-icon-arrow-right">
          <el-breadcrumb-item :to="{ path: '/layout/layoutshouye' }">首页</el-breadcrumb-item>
          <el-breadcrumb-item>提交商品</el-breadcrumb-item>
        </el-breadcrumb>
      </div>
      <!-- 表单数据 -->
      <div class="myfrom">
        <el-form :model="goodsForm" status-icon :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm">
          <el-form-item label="类目选择" prop="goodsCategory" required>
            <el-select v-model="goodsForm.goodsCategory" placeholder="请选择">
              <el-option
                v-for="item in options"
                :key="item.value"
                :label="item.label"
                :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="次级分类" prop="goodsCategoryname">
            <el-button type="primary" @click="dialogVisible = true">次级分类(可选)</el-button>
            <span>{{goodsForm.goodsCategoryname}}</span>
          </el-form-item>
          <el-form-item label="商品名称" prop="goodsName">
            <el-input v-model="goodsForm.goodsName"></el-input>
          </el-form-item>
          <el-form-item label="底价" prop="goodsPrice">
            <el-input v-model="goodsForm.goodsPrice"></el-input>
          </el-form-item>
          <el-tooltip class="item" effect="dark" content="上传一张主要图片" placement="bottom-start">
            <el-form-item label="商品图片" prop="goodsImg" required>
              <el-button type="primary" @click="dialogVisibleImg = true">上传图片</el-button>
              <img v-if="goodsForm.goodsImg" :src="goodsForm.goodsImg" height="100px" style="margin:10px;display:inline-block" alt="">
            </el-form-item>
          </el-tooltip>
          <el-tooltip class="item" effect="dark" content="该项可以选择" placement="bottom-start">
            <el-form-item label="相关图片" prop="goodsRelateimg">
              <el-button type="primary" @click="dialogVisibleRelateimg = true">上传相关图片</el-button>
              <img v-show="goodsForm.goodsRelateimg" v-for="(img,index) in fileList" :key="index" :src="img.url" height="100px" style="margin:10px;display:inline-block" alt="">
            </el-form-item>
          </el-tooltip>
          <el-form-item label="提交时间" required>
            <!-- <el-date-picker type="date" placeholder="选择日期" v-model="goodsForm.subTime" style="width: 30%;"></el-date-picker> -->
             <el-col :span="11">
                <el-form-item prop="date1">
                  <el-date-picker type="date" placeholder="选择日期" v-model="date1" style="width: 100%;"></el-date-picker>
                </el-form-item>
              </el-col>
              <el-col class="line" :span="2">:</el-col>
              <el-col :span="11">
                <el-form-item prop="date2">
                  <el-time-picker placeholder="选择时间" 
                    value-format="HH:mm:ss"
                   v-model="date2" style="width: 100%;"></el-time-picker>
                </el-form-item>
              </el-col>
          </el-form-item>
          <!-- 富文本编辑//官网https://www.wangeditor.com/doc/
            使用：
            1、安装npm i wangeditor
            2、引入 import E from "wangeditor"
            3、使用
              this.editor = new E("#main")
              this.editor.create()

              常用配置：
              1、清空内容
                editor.txt.clear()  清空编辑器内容
              2、设置内容
                editor.txt.html('') 获取html
              3、配置菜单
                1、onchange回调函数
      
           -->
          <el-form-item label="商品描述" prop="goodsContent" style="z-index: 100;">
            <!-- <textarea name="" id="" cols="30" rows="10" style="border:1px solid #000"></textarea> -->
            <WangEditor ref="myEditor" @sendEditor="sendEditor"/>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="getSubmitTime();submitForm('ruleForm')">确定提交</el-button>
            <el-button @click="clearForm()">重置</el-button>
          </el-form-item>
        </el-form>
        <!-- 1、弹框---类的选择 -->
        <el-dialog
          title="次级分类"
          :visible.sync="dialogVisible"
          width="30%"
          style="z-index:101"
          :before-close="handleClose">
          <!-- 
            :props:="props"  props	配置选项，具体看下表
            :load="loadNode" load	加载子树数据的方法，仅当 lazy 属性为true 时生效
            lazy  lazy	是否懒加载子节点，需与 load 方法结合使用
            show-checkbox show-checkbox	节点是否可被选择
            @node-click 点击eltree获取数据
            accordion 是否每次只只打开一个同级树节点展开
           -->
            <el-tree
              :props="props"
              :load="loadNode"
              lazy
              accordion
              @node-click="nodeClick">
            </el-tree>
            <span slot="footer" class="dialog-footer">
              <el-button @click="dialogVisible = false">取 消</el-button>
              <el-button type="primary" @click="showTreeData">确 定</el-button>
            </span>
        </el-dialog>

        <!-- 2、内弹框--上传主要图片 -->
        <el-dialog
          title="上传图片"
          :visible.sync="dialogVisibleImg"
          width="30%"
          :before-close="handleClose">
             <!-- 
              ref="upload" id-获取dom元素
              action	必选参数，上传的地址
              on-preview	点击文件列表中已上传的文件时的钩子
              on-remove	文件列表移除文件时的钩子
              on-success	文件上传成功时的钩子
              on-error	文件上传失败时的钩子
              on-progress	文件上传时的钩子
              file-list	上传的文件列表, 例如: [{name: 'food.jpg', url: 'https://xxx.cdn.com/xxx.jpg'}] 数组类型
              http-request  覆盖默认的上传行为，可以自定义上传的实现
              方法：
              submit	手动上传文件列表
              limit	最大允许上传个数
            -->
            <el-upload
              class="upload-demo"
              ref="upload"
              :action="'http://localhost:8080/api/getimg/upload'"
              :on-preview="handlePreview"
              :on-remove="handleRemove"
              :on-success="successUpload"
              :http-request="upload"
              :limit = '1'
              :auto-upload="false">
              <el-button slot="trigger" size="small" type="primary">选取文件</el-button>
              <el-button style="margin-left: 10px;" size="small" type="success" @click="submitUpload">上传到服务器</el-button>
            </el-upload>
            <span slot="footer" class="dialog-footer">
              <el-button @click="dialogVisibleImg = false">取 消</el-button>
              <el-button type="primary" @click="showImg">确 定</el-button>
            </span>
        </el-dialog>
        <!-- 3、上传次要图片 -->
        <el-dialog
          title="上传相关图片"
          :visible.sync="dialogVisibleRelateimg"
          width="30%"
          :before-close="handleClose">
            <el-upload
              class="upload-demo"
              ref="rupload"
              :action="'http://localhost:8080/api/getRelateimg/upload'"
              :on-preview="handlePreview"
              :on-remove="handleRemove"
              :on-success="successUpload"
              :file-list="fileList"
              :http-request="Rupload"
              :auto-upload="false">
              <el-button slot="trigger" size="small" type="primary">选取文件</el-button>
              <el-button style="margin-left: 10px;" size="small" type="success" @click="submitRupload">上传到服务器</el-button>
            </el-upload>
            <span slot="footer" class="dialog-footer">
              <el-button @click="dialogVisibleRelateimg = false">取 消</el-button>
              <el-button type="primary" @click="showRelateimg">确 定</el-button>
            </span>
        </el-dialog>
      </div>
  </div>
</template>

<script>
import WangEditor from '@/components/WangEditor'
import axios from 'axios'
import { mapState,mapGetters } from "vuex";
export default {
    name:"UserSubmit",
    components:{
      WangEditor
    },
    data() {
      return {
        // outerVisible: false,//外弹框
        url:'',//图片地址服务器
        relateUrl:'',
        fileList: [],
        dialogVisible: false,
        innerVisible:false,//内弹框
        dialogVisibleImg:false,//图片弹窗
        dialogVisibleRelateimg:false,
        treedata:{},
        date1:'',
        date2:'',
        userId:'',
        timer:null,
        userAccount:'',
        goodsForm: {//表单容器对象
          goodsName: '',
          goodsContent: '',
          goodsPrice: '',
          goodsImg:'',
          goodsRelateimg: '',
          goodsCategory: '',
          goodsCategoryname: '',
          subTime:''//商品提交时间
        },
        props: {//分类栏设置
          label: 'title',
          // children: 'zones',
          // isLeaf: 'leaf'
        },
        rules: {//element组件校验规则
          goodsName: [
            { required: true, message: '请输入商品名称', trigger: 'blur' },
            { min: 4, max: 255, message: '长度在 4 到 255 个字符', trigger: 'blur' }
          ],
          goodsPrice: [
            { required: true, message: '请输入你心中的最低竞拍价', trigger: 'blur' }
          ],
          subTime: [
            { type: 'date', required: false, message: '请选择日期', trigger: 'change' }
          ],
        },
        options: [],
      }
    },
    created() {
      this.getOption()
    },
    mounted() {
      this.userAccount = this.$store.state.user.userlist.userAccount
      this.userId = this.$store.state.user.userlist.userId
      console.log("nnn",this.userAccount,this.userId)
      this.$store.dispatch("categoryList"); 
      // this.$store.dispatch("getuserlist");
    },
    computed: {
        ...mapState({
          categoryList: (state) => state.paimai.categoryList,
          // userlist: (state) => state.user.userlist,
        }),
        // ...mapGetters(['getCategoryList'])
    },
    methods: {
      //接收管理员删除的自己商品的信息
      sendMessage(){

      },
      // 清空表单
      clearForm(){
          // 清空表单
          this.$refs.ruleForm.resetFields()
          // 单独清空富文本编辑器
          this.$refs.myEditor.editor.txt.clear()
          this.date1 = ''
          this.date2 = ''
          // this.newsForm.newsImg = ''
        },
      // 提交所填的表
      submitForm(formName){
        console.log(this.$refs[formName])
        this.$refs[formName].validate((valid)=>{
          if(valid){
            axios.get("http://localhost:8080/api/addGoodssubmit/addlist",{
              params:{
                userId:this.userId,
                userAccount:this.userAccount,
                goodsName:this.goodsForm.goodsName,
                goodsCategory:this.goodsForm.goodsCategory,
                goodsCategoryname:this.goodsForm.goodsCategoryname,
                goodsImg:this.goodsForm.goodsImg,
                goodsRelateimg:this.goodsForm.goodsRelateimg,
                goodsContent:this.goodsForm.goodsContent,
                goodsPrice:this.goodsForm.goodsPrice,
                subTime:this.goodsForm.subTime
              }
            }).then(
              res=>{
                this.$message({
                  message:'添加成功',
                  type:'success'
                })
                this.clearForm()
                // console.log("添加成功")
              },
              error=>{
                console.log("b",error.message)
              }
            )
            console.log("获取输入信息",this.goodsForm)
          }else{
            console.log("提交错误")
            return false
          }
        })
      },
      // 时间转换
      formatDateTime (date) {
        var date = new Date(date)
        var y = date.getFullYear();
        var m = date.getMonth() + 1;
        m = m < 10 ? ('0' + m) : m;
        var d = date.getDate();
        d = d < 10 ? ('0' + d) : d;
        // return y + '-' + m + '-' + d+' '+h+':'+minute;
        return y + '-' + m + '-' + d
      },
      // 获取提交时间
      getSubmitTime(){
          // this.goodsForm.subTime = String(this.date1).slice(0,15) + String(this.date2).slice(15,24)
          var data = this.formatDateTime(this.date1)
          this.goodsForm.subTime = data + ' ' + this.date2

          console.log(this.goodsForm.subTime)
      },
      // 接收wangeditor文本数据
      sendEditor(val){
        this.goodsForm.goodsContent = val
        // console.log("222",this.goodsForm.goodsContent)
      },
      // 展示图片
      showRelateimg(){
        this.dialogVisibleRelateimg = false
        // this.relateUrl = this.url[1]
        // console.log(this.fileList,this.fileList[0].url)
        for(var i=0;i<this.fileList.length;i++){
          this.relateUrl += this.fileList[i].url + ";"
        }
        // console.log("aaa",this.relateUrl)
        this.goodsForm.goodsRelateimg = this.relateUrl
      },
      Rupload(f) {
        // console.log(f)
        //  1. 获取表单数据   fromData 表单数据
        let fromData = new FormData()
        fromData.append("file", f.file)
        // 2. 发起请求
        axios({
          method: 'post',
          url: f.action,
          data: fromData
        }).then(res => {
          // 3. 请求成功之后  图片回显
          console.log("111",res,f)
          // this.relateUrl = res.data.url 
          this.fileList.push({name:f.file.name,url:res.data.url})
          console.log("555",this.fileList,this.fileList[0])
          this.$message({
            message:'图片上传成功',
            type:'success'
          })
        })
      },
      submitRupload() {
        this.$refs.rupload.submit();
      },
      showImg(){
        this.dialogVisibleImg = false
        this.goodsForm.goodsImg = this.url
      },
      // 获取图片地址  覆盖默认的上传行为，可以自定义上传的实现
      upload(f) {
        // console.log(f)
        //  1. 获取表单数据   fromData 表单数据
        let fromData = new FormData()
        fromData.append("file", f.file)
        // 2. 发起请求
        axios({
          method: 'post',
          url: f.action,
          data: fromData
        }).then(res => {
          // 3. 请求成功之后  图片回显
          console.log(res)
          this.url = res.data.url
          this.$message({
            message:'图片上传成功',
            type:'success'
          })
        })
      },
      // 上传成功的函数
      successUpload(response,file,fileList){
        console.log("上传成功了",response,file,fileList)
        this.$message({
          message:'图片上传成功',
          type:'success'
        })
      },
      // 点击上传按钮的事件
      submitUpload() {
        this.$refs.upload.submit();
      },
      handleRemove(file, fileList) {
        console.log(file, fileList);
      },
      handlePreview(file) {
        console.log(file);
      },
      handleClose(done) {
        this.$confirm('确认关闭？')
          .then(_ => {
            done();
          })
          .catch(_ => {});
      },
      // 分类加载
      loadNode(node, resolve) {
        // console.log("b",node)
        // console.log("v",this.categoryList)
        if (node.level === 0) {
          var res = []
          for(var i=0;i<this.categoryList.length;i++){
            if(this.categoryList[i]!= undefined){
              var obj = {
                title: this.categoryList[i].categoryName,
              }
              res.push(obj)
            }
          }
          console.log(res)
          return resolve(res);
        }
        if (node.level > 3) return resolve([]);

        var hasChild;
        if (node.data.title == '校园跳蚤市场') {
          hasChild = 1;
        } else if (node.data.title == '手机') {
          hasChild = 2;
        } else if(node.data.title == '课外书'){
          hasChild = 3
        }else if(node.data.title == '小物件'){
          hasChild = 4
        }else if(node.data.title == '二手书'){
          hasChild = 5
        }else if(node.data.title == '文艺'){
          hasChild = 6
        }else if(node.data.title == '体育器材'){
          hasChild = 7
        }else if(node.data.title == '人文社科'){
          hasChild = 8
        }else if(node.data.title == '毛绒玩具'){
          hasChild = 9
        }else if(node.data.title == '乐器'){
          hasChild = 10
        }else if(node.data.title == '艺术品'){
          hasChild = 11
        }else if(node.data.title == '生活类'){
          hasChild = 12
        }else if(node.data.title == '电子音像类'){
          hasChild = 13
        }else if(node.data.title == '二手手机'){
          hasChild = 14
        }else if(node.data.title == '运营商'){
          hasChild = 15
        }else{
          hasChild = 0;
        }
        
        this.timer = setTimeout(() => {
          var data;
          var res1 = []
          for(var j = 0;j<this.categoryList.length;j++){
          if(this.categoryList[j].categoryChild.length != 0){
            for(var k=0;k<this.categoryList[j].categoryChild.length;k++){
              var obj1 = {
                title: this.categoryList[j].categoryChild[k].categoryName
              }
              res1.push(obj1)
            }
          }else{
            res1.push({title:''})
          }
        }
        // console.log("res",res1.slice(0,11))
          if (hasChild==1) {
            data = res1.slice(0,11);
          } else if (hasChild==2) {
            data = res1.slice(11,14);
          }else if (hasChild==3) {
            data = [{title:'三体'},{title:'九章算术'},{title:'艺术书'},{title:'其他'}];
          }else if (hasChild==4) {
            data = [{title:'小风扇'},{title:'计算器'},{title:'数据线'},{title:'钥匙扣/邮票'}];
          }else if (hasChild==5) {
            data = [{title:'计算机类'},{title:'数学'},{title:'英语'},{title:'文学'},{title:'法律'},{title:'基础课程'}];
          }else if (hasChild==6) {
            data = [{title:'小说'},{title:'文学'},{title:'青春文学'},{title:'传记'},{title:'艺术'}];
          }else if (hasChild==7) {
            data = [{title:'跳绳'},{title:'滑板'},{title:'网球拍'},{title:'篮球'},{title:'羽毛球拍'}];
          }else if (hasChild==8) {
            data = [{title:'历史'},{title:'哲学'},{title:'国学'},{title:'政治/军事'},{title:'法律'},{title:'人文社科'},{title:'心理学'},{title:'文化'},{title:'社会科学'}];
          }else if (hasChild==9) {
            data = [{title:'柴犬'},{title:'猪公仔'},{title:'大熊泰迪'},{title:'哈士奇抱枕'}];
          }else if (hasChild==10) {
            data = [{title:'吉他'},{title:'口琴'},{title:'笛子'},{title:'小提琴'},{title:'尤克里里'}];
          }else if (hasChild==11) {
            data = [{title:'哆啦A梦手机支架'},{title:'皮卡丘'},{title:'素描'},{title:'书法'},{title:'对联'},{title:'漫画'},{title:'插画'}];
          }else if (hasChild==12) {
            data = [{title:'书架'},{title:'书桌'},{title:'水壶'}];
          }else if (hasChild==13) {
            data = [{title:'MP3'},{title:'MP4'},{title:'U盘'},{title:'CD'}];
          }else if (hasChild==14) {
            data = [{title:'华为'},{title:'小米/红米'},{title:'苹果'},{title:'oppo'},{title:'vivo'},{title:'魅族'},{title:'索尼'}];
          }else if (hasChild==15) {
            data = [{title:'合约机'},{title:'选号中心'},{title:'装宽带'},{title:'办套餐'}];
          }else {
            data = [];
          }
          resolve(data);
        }, 500);
      },
      // 获取分类节点
      nodeClick(data,node){
        console.log("x",data,node,data.title,node.level)
        if(node.level == 3){
          this.treedata = data.title
        }else{
          this.treedata = ''
        }
        console.log(this.treedata)
      },
      // 显示tree数据
      showTreeData(){
        // 关闭窗口
        this.dialogVisible = false
        this.goodsForm.goodsCategoryname = this.treedata
      },
      getOption(){
        var res = []
        this.timer = setTimeout(()=>{
          var c = this.$store.state.user.categoryList
          for(var i=0;i<c.length;i++){
          if(c[i]!= undefined){
            var obj = {
              value: c[i].categoryName,
              label: c[i].categoryName
            }
            res.push(obj)
          }
        }
        this.options = res
        // console.log("a",this.options,res)
        },500)
      },
    },
    beforeDestroy() {    //页面关闭时清除定时器  
      clearInterval(this.timer);
    },
}
</script>

<style lang="less" scoped>
.userSubmit{
  margin: 20px;
  .title{
    padding: 10px;
    background: #fff;
    border: 1px solid #eee;
    margin-bottom: 20px;
  }
  .myfrom{
    background: #fff;
    padding: 10px;
    padding-right: 30px;
  }
}
.line{
  text-align: center;
}
</style>